package com.ruoyi.system.service.impl.fxImpl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.dto.FxStoreGoodDto;
import com.ruoyi.system.domain.dto.FxSupplierGoodDto;
import com.ruoyi.system.domain.dto.GoodInventoryDto;
import com.ruoyi.system.domain.fx.*;
import com.ruoyi.system.domain.vo.FxStoreGoodVo;
import com.ruoyi.system.domain.vo.FxSupplierGoodMtVO;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.fx.*;
import com.ruoyi.system.service.fx.IFxStoreGoodService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;


/**
 * 店铺商品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class FxStoreGoodServiceImpl implements IFxStoreGoodService {
    @Autowired
    private FxStoreGoodMapper fxStoreGoodMapper;
    @Autowired
    private FxSupplierGoodMapper supplierGoodMapper;
    @Autowired
    private FxGoodclassifyMapper fxGoodclassifyMapper;
    @Autowired
    private FxStoreMapper fxStoreMapper;
    @Autowired
    private FxUserMapper fxUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询店铺商品
     *
     * @param id 店铺商品主键
     * @return 店铺商品
     */
    @Override
    @Transactional
    public FxStoreGoodVo selectFxStoreGoodById(Long id, Long supplierGoodId) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        boolean isFirstDayOfMonth = today.getDayOfMonth() == 1;
        FxStoreGood storeGood = new FxStoreGood();
        if (StringUtils.isNotNull(id)) {
            storeGood = fxStoreGoodMapper.selectFxStoreGoodByIdOrSupplierGoodId(id, supplierGoodId, null);
        }
        if (StringUtils.isNotNull(supplierGoodId)) {
            Long userId = SecurityUtils.getUserId();
            FxUser fxUser = new FxUser();
            fxUser.setSysUserid(userId);
            List<FxUser> userList = fxUserMapper.selectFxUserList(fxUser);
            if (StringUtils.isEmpty(userList) || StringUtils.isNull(userList.get(0).getStoreId())) {
                throw new GlobalException("无当前商品");
            }
            fxUser = userList.get(0);
            storeGood = fxStoreGoodMapper.selectFxStoreGoodByIdOrSupplierGoodId(id, supplierGoodId, fxUser.getStoreId());
            if (StringUtils.isNull(storeGood)) {
                throw new GlobalException("无当前商品");
            }
        }

        FxStore fxStore = fxStoreMapper.selectFxStoreById(storeGood.getStoreId().longValue());
        FxSupplierGood fxSupplierGood = supplierGoodMapper.selectFxSupplierGoodById(storeGood.getGoodId());
        FxStoreGoodVo goodVo = new FxStoreGoodVo();
        BeanUtil.copyProperties(fxSupplierGood, goodVo);
        BeanUtils.copyProperties(storeGood, goodVo);
        if (StringUtils.isNotEmpty(goodVo.getSpecifications())) {
            List<String> list = Arrays.asList(goodVo.getSpecifications().split(";"));
            goodVo.setSpecificationsList(list);
        }
        goodVo.setStoreName(fxStore.getStoreName());
//                .setGoodName(fxSupplierGood.getGoodName())
//                .setGoodDetail(fxSupplierGood.getGoodDetail())
//                .setGoodImg(fxSupplierGood.getGoodImg())
//                .setGoodDesc(fxSupplierGood.getGoodDesc())
//                .setGoodText(fxSupplierGood.getGoodText())
//                .setRetailPrice(fxSupplierGood.getRetailPrice())
//                .setMemberPrice(fxSupplierGood.getMemberPrice())
//                .setQrCodeUrl(fxSupplierGood.getQrCodeUrl())
//                .setSource(fxSupplierGood.getSource())
//                .setClassOneId(fxSupplierGood.getClassOneId())
//                .setClassTwoId(fxSupplierGood.getClassTwoId())
//                .setClassThreeId(fxSupplierGood.getClassThreeId())
//                .setClassOneName(fxSupplierGood.getClassOneName())
//                .setClassTwoName(fxSupplierGood.getClassTwoName())
//                .setClassThreeName(fxSupplierGood.getClassThreeName())
//                .setTradePrice(StringUtils.isNotNull(fxSupplierGood.getTradePrice()) ? fxSupplierGood.getTradePrice().toString() : "0");
        return goodVo;
    }

    /**
     * 查询店铺商品列表
     *
     * @param fxStoreGood 店铺商品
     * @return 店铺商品
     */
    @Override
    public List<FxStoreGoodVo> selectFxStoreGoodList(FxStoreGood fxStoreGood,String goodName,String storeName) {
        // 获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        // 判断是否是超级管理员
        List<Integer> role = sysUserRoleMapper.selectByUserId(userId);
        Integer storeId;
        FxUser fxUser = new FxUser();
        fxUser.setSysUserid(userId);
        List<FxUser> userList = fxUserMapper.selectFxUserList(fxUser);
        if (StringUtils.isNotEmpty(userList)) {
            FxUser user = userList.get(0);
            storeId = Convert.toInt(user.getStoreId()); // 拿到登录人店铺id
        } else {
            storeId = null;
        }
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        boolean isFirstDayOfMonth = today.getDayOfMonth() == 1;
        List<FxStoreGoodVo> goodVoList = new ArrayList<>(); // 创建 商品列表 准备返回
        fxStoreGood.setDelFlag(0); // 查找未删除的商品
        if (role.contains(1) || role.contains(6)) {
            storeId = null;
        }
        fxStoreGood.setStoreId(storeId);
        startPage();
        List<FxStoreGood> goodList = fxStoreGoodMapper.selectFxStoreGoodList(fxStoreGood); // 获取未删除全部商品
        if (goodList.size() == 0) {
            return goodVoList;
        }
        List<Integer> storeIds = goodList.stream().map(FxStoreGood::getStoreId).distinct().collect(Collectors.toList()); // 拿到全部商品id 店铺id
        List<FxStore> storeList = fxStoreMapper.selectFxStoreListByIds(storeIds); // 查找 店铺集合
        Map<Long, FxStore> storeMap = storeList.stream().collect(Collectors.toMap(FxStore::getId, fxStore -> fxStore)); // 转为 map key 为店铺id value 为店铺
        List<Long> goodIdList = goodList.stream().map(FxStoreGood::getGoodId).distinct().collect(Collectors.toList());
        List<FxSupplierGood> supplierGoodList = supplierGoodMapper.selectFxSupplierGoodListByGoodIds(goodIdList);
        Map<Long, FxSupplierGood> goodMap = supplierGoodList.stream().collect(Collectors.toMap(FxSupplierGood::getId, fxSupplierGood -> fxSupplierGood));
        for (FxStoreGood storeGood : goodList) {
            if (isFirstDayOfMonth)
                storeGood.setMonthSellCount(0); //是1号 设置月销售为0
            FxStoreGoodVo goodVo = new FxStoreGoodVo();
            FxSupplierGood fxSupplierGood = goodMap.get(storeGood.getGoodId());
            FxStore fxStore = storeMap.get(storeGood.getStoreId().longValue());
            if (StringUtils.isNotNull(fxStore)) { // 店铺不为空 进入展示商品
                BeanUtils.copyProperties(storeGood, goodVo);
                goodVo.setStoreName(fxStore.getStoreName())
                        .setGoodName(fxSupplierGood.getGoodName())
                        .setGoodDetail(fxSupplierGood.getGoodDetail())
                        .setGoodImg(fxSupplierGood.getGoodImg())
                        .setGoodDesc(fxSupplierGood.getGoodDesc())
                        .setGoodText(fxSupplierGood.getGoodText())
                        .setRetailPrice(fxSupplierGood.getRetailPrice())
                        .setQrCodeUrl(fxSupplierGood.getQrCodeUrl())
                        .setSupplierName(fxSupplierGood.getCreaterName() != null ? fxSupplierGood.getCreaterName() : fxSupplierGood.getSupplierName())
                        .setSource(fxSupplierGood.getSource())
                        .setGoodClassify(fxSupplierGood.getClassTwoId())
                        .setTradePrice(fxSupplierGood.getTradePrice().toString())
                        .setGoodStatus(fxSupplierGood.getStatus());
                goodVoList.add(goodVo);
            }
        }
        if (!StringUtils.isEmpty(storeName)){
            goodVoList=goodVoList.stream().filter(x ->x.getStoreName().contains(storeName)).collect(Collectors.toList());
        }
        if (!StringUtils.isEmpty(goodName)){
            goodVoList=goodVoList.stream().filter(x ->x.getGoodName().contains(goodName)).collect(Collectors.toList());
        }
//        goodVoList = goodVoList.stream().filter(goodVo -> Objects.equals(goodVo.getStoreId(), storeId)).collect(Collectors.toList());
        return goodVoList;
    }

    @Override
    public List<FxStoreGoodVo> selectStoreGoodList(FxStoreGoodDto goodDto) {

        List<FxStoreGoodVo> goodList = fxStoreGoodMapper.selectStoreGoodList(goodDto); // 获取未删除全部商品

        List<Long> goodsIds = goodList.stream().map(FxStoreGoodVo::getGoodId).collect(Collectors.toList());
        if(!goodsIds.isEmpty()){
            goodDto.setGoodIds(goodsIds.toArray(new Long[goodsIds.size()]));
            List<FxStoreGoodVo> list = fxStoreGoodMapper.selectStoreGoodSonList(goodDto);
            goodList.addAll(list);
        }
        if (StringUtils.isEmpty(goodList)) {
            return new ArrayList<>();
        }
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        boolean isFirstDayOfMonth = today.getDayOfMonth() == 1;
        for (FxStoreGoodVo goodVo : goodList) {
            if (isFirstDayOfMonth)
                goodVo.setMonthSellCount(0); //是1号 设置月销售为0
        }
        return goodList;
    }

    @Override
    public List<FxStoreGoodVo> getStoreGoodList(FxStoreGoodDto goodDto) {

        List<FxStoreGoodVo> goodList = fxStoreGoodMapper.selectStoreGoodList(goodDto); // 获取未删除全部商品
        if (StringUtils.isEmpty(goodList)) {
            return new ArrayList<>();
        }
        //查找子商品
        Long[] longs = goodList.stream().map(FxStoreGoodVo::getId).toArray(Long[]::new);
        FxStoreGoodDto fxStoreGoodDto = new FxStoreGoodDto();
        fxStoreGoodDto.setGoodIds(longs);
        //装成map集合
        Map<Long, List<FxStoreGoodVo>> map = new HashMap<>();
        List<FxStoreGoodVo> fxStoreGoodVos = fxStoreGoodMapper.selectStoreGoodSonList(fxStoreGoodDto);
            for (FxStoreGoodVo fxStoreGoodVo : fxStoreGoodVos) {
                if (map.containsKey(fxStoreGoodVo.getParentId())){
                    List<FxStoreGoodVo> item = map.get(fxStoreGoodVo.getParentId());
                    item.add(fxStoreGoodVo);
                }else {
                    List<FxStoreGoodVo> item = new ArrayList<>();
                    item.add(fxStoreGoodVo);
                    map.put(fxStoreGoodVo.getParentId(),item);
                }
            }
        //填充到主商品
        for (FxStoreGoodVo fxStoreGoodVo : goodList) {
            if (map.containsKey(fxStoreGoodVo.getId())){
                List<FxStoreGoodVo> item = map.get(fxStoreGoodVo.getId());
                fxStoreGoodVo.setGoodVoList(item);
            }else {
                fxStoreGoodVo.setGoodVoList(new ArrayList<>());
            }
        }


        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        boolean isFirstDayOfMonth = today.getDayOfMonth() == 1;
        for (FxStoreGoodVo goodVo : goodList) {
            if (isFirstDayOfMonth)
                goodVo.setMonthSellCount(0); //是1号 设置月销售为0
        }
        return goodList;
    }

    /**
     * 查询门店商品
     *
     * @param fxStoreGood
     * @return
     */
    @Override
    public Map<Long, List<FxStoreGoodVo>> selectFxStoreGoodMap(FxStoreGood fxStoreGood) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        boolean isFirstDayOfMonth = today.getDayOfMonth() == 1;
        if (fxStoreGood.getStoreId() == null)
            return new HashMap<>();
        // 获取门店 id
        Long storeId = Long.valueOf(fxStoreGood.getStoreId());
        FxStoreGoodDto fxStoreGoodDto = new FxStoreGoodDto();
        fxStoreGoodDto.setStoreId(storeId);
        List<FxStoreGoodVo> goodVoList = fxStoreGoodMapper.selectAppGoodList(fxStoreGoodDto);
        if (CollectionUtils.isEmpty(goodVoList))
            return new HashMap<>();
        if (isFirstDayOfMonth)
            goodVoList.stream().forEach(g -> g.setMonthSellCount(0));
        Map<Long, List<FxStoreGoodVo>> goodsMap = goodVoList.stream().collect(Collectors.groupingBy(FxStoreGoodVo::getGoodClassify));
        return goodsMap;
    }

    @Override
    public List<FxGoodclassify> getLeftClassifyByStoreId(int  storeId){
        List<FxGoodclassify> classifyList = fxGoodclassifyMapper.selectLeftClassifyByStoreId(storeId);
        return  classifyList;
    }

    @Override
    @Transactional
    public void importDp(MultipartFile file, HttpServletResponse response) {
        ExcelUtil<FxSupplierGoodMtVO> util = new ExcelUtil<>(FxSupplierGoodMtVO.class);
        try {
            List<FxSupplierGoodMtVO> fxSupplierGoodMtVOS = util.importExcel(file.getInputStream());
            //父模板
            Map<String, FxSupplierGoodMtVO> map = new HashMap<>();
            //子模板
            Map<String, List<FxSupplierGoodMtVO>> mapSon = new HashMap<>();

            for (FxSupplierGoodMtVO fxSupplierGoodMtVO : fxSupplierGoodMtVOS) {
                // 父模板装一个map
                if (!map.containsKey(fxSupplierGoodMtVO.getGoodName())){
                    fxSupplierGoodMtVO.setParentId(0L);
                    map.put(fxSupplierGoodMtVO.getGoodName(),fxSupplierGoodMtVO);
                    //子模板装另一个map
                }else{
                    String itemName=fxSupplierGoodMtVO.getGoodName();
                    if (mapSon.containsKey(fxSupplierGoodMtVO.getGoodName())){
                        fxSupplierGoodMtVO.setGoodName(fxSupplierGoodMtVO.getSonGoodName());
                        mapSon.get(itemName).add(fxSupplierGoodMtVO);
                    }else {
                        List<FxSupplierGoodMtVO> list = new ArrayList<>();

                        fxSupplierGoodMtVO.setGoodName(fxSupplierGoodMtVO.getSonGoodName());
                        list.add(fxSupplierGoodMtVO);
                        mapSon.put(itemName,list);
                    }
                }
            }
            //批量新增父模板获取id
            List<FxSupplierGoodMtVO> fxSupplierGoodMts = new ArrayList<>(map.values());

            //插入父模板

            Map<String, Object> map1 = this.saveBath(fxSupplierGoodMts);
            List<FxSupplierGood> fxSupplierGoods =(List<FxSupplierGood>) map1.get("fxSupplierGoods");

            String fatherMsg =(String) map1.get("msg");

            Map<String, FxSupplierGood> goodMap = fxSupplierGoods.stream().collect(Collectors.toMap(FxSupplierGood::getGoodName, g -> g));


            //遍历子模板填充父id
            List<FxSupplierGoodMtVO> sonFxSupplierGoodMtVO = new ArrayList<>();
            mapSon.forEach((k,v)->{
                if (goodMap.containsKey(k)){
                    FxSupplierGood fxSupplierGood = goodMap.get(k);
                    for (FxSupplierGoodMtVO fxSupplierGoodMtVO : v) {

                        fxSupplierGoodMtVO.setParentId(fxSupplierGood.getId());
                    }
                    sonFxSupplierGoodMtVO.addAll(v);
                }

            });
            //批量新增子模板
            String s = this.saveSonBath(sonFxSupplierGoodMtVO);

            StringBuilder sb=new StringBuilder();
            if (StringUtils.isNotEmpty(fatherMsg)){
                sb.append(fatherMsg);
                if (StringUtils.isNotEmpty(s)){
                    sb.setLength(sb.length()-1);
                    sb.append(s.substring(1));
                }
            }

            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSON.toJSONString(AjaxResult.success("导入成功\n"+sb)));

        } catch (IOException e) {
          throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public int editAll(List<FxSupplierGoodDto> fxSupplierGoodDtos) {
        if (CollectionUtils.isEmpty(fxSupplierGoodDtos)){
            throw new RuntimeException("至少需要一个商品");
        }
        //拿到母商品
        FxSupplierGoodDto fxSupplierGoodDto = fxSupplierGoodDtos.get(0);
        //修改或新增
        if (ObjectUtils.isEmpty(fxSupplierGoodDto.getId())){
            this.insertFxStoreGood(fxSupplierGoodDto);
        }else {
            this.updateFxStoreGood(fxSupplierGoodDto);
        }
        for (int i = 0; i < fxSupplierGoodDtos.size(); i++) {
            if (i==0){
                continue;
            }
            if (ObjectUtils.isEmpty(fxSupplierGoodDtos.get(i).getId())){
                fxSupplierGoodDtos.get(i).setParentId(fxSupplierGoodDto.getId());
                this.insertFxStoreGood( fxSupplierGoodDtos.get(i));
            }else {
                this.updateFxStoreGood( fxSupplierGoodDtos.get(i));
            }

        }
     return 1;
    }


    public Map<String,Object> saveBath(List<FxSupplierGoodMtVO> fxSupplierGoodMts) {
        Long userId = SecurityUtils.getUserId();
        FxUser fxUser = fxUserMapper.selectFxUserByUserId(userId); // 拿到用户信息
        if (ObjectUtils.isEmpty(fxUser)||ObjectUtils.isEmpty(fxUser.getStoreId())) {
            throw new GlobalException("人员信息异常");
        }
        FxStore fxStore = fxStoreMapper.selectFxStoreById(fxUser.getStoreId());
        if (StringUtils.isNull(fxStore.getRegion()))
            throw new GlobalException("店铺地区信息异常");

        List<String> goodNames = fxSupplierGoodMts.stream().map(FxSupplierGoodMtVO::getGoodName).collect(Collectors.toList());
        //查询该店铺下的所有母商品
         List<String> goodNameList=supplierGoodMapper.selectAllOne(goodNames,fxStore.getId());
        //去除已经存在的母商品
        fxSupplierGoodMts.removeIf(fxSupplierGoodMt -> goodNameList.contains(fxSupplierGoodMt.getGoodName()));

        List<FxStoreGood> fxStoreGoods = new ArrayList<>();
        List<FxSupplierGood> fxSupplierGoods = new ArrayList<>();
        Date nowDate = DateUtils.getNowDate();
        //填充 fx_store_good 和  fx_supplier_good
        for (FxSupplierGoodMtVO fxSupplierGoodMt : fxSupplierGoodMts) {
            Long goodId = Convert.toLong(System.currentTimeMillis() + "" + ThreadLocalRandom.current().nextInt(100, 1000));
            //FxStoreGood
            FxStoreGood fxStoreGood = new FxStoreGood();
            fxStoreGood.setId(goodId);
            fxStoreGood.setCreateUser(Integer.parseInt(userId.toString()));
            fxStoreGood.setCreateTime(nowDate);
            fxStoreGood.setCounts(Integer.valueOf(fxSupplierGoodMt.getCounts().toString()));
            fxStoreGood.setTotalSellCount(0);
            fxStoreGood.setStoreId(Integer.valueOf(fxStore.getId().toString()));
            fxStoreGood.setIsInitiate(Integer.valueOf(fxSupplierGoodMt.getIsInitiate()));
            fxStoreGood.setGoodId(goodId);
            //FxSupplierGood
            FxSupplierGood fxSupplierGood = new FxSupplierGood();
            fxSupplierGood.setCreateTime(nowDate);
            fxSupplierGood.setCreateUser(userId);
            fxSupplierGood.setId(goodId);
            fxSupplierGood.setParentId(0L);
            fxSupplierGood.setSource(2);
            fxSupplierGood.setUserId(userId);
            fxSupplierGood.setRegion(Convert.toStr(fxStore.getRegion()));
            fxSupplierGood.setGoodName(fxSupplierGoodMt.getGoodName());
            fxSupplierGood.setTradePrice(fxSupplierGoodMt.getTradePrice());
            fxSupplierGood.setRetailPrice(fxSupplierGoodMt.getRetailPrice());
            fxSupplierGood.setMemberPrice(fxSupplierGoodMt.getMemberPrice());
            fxSupplierGood.setGrandCounts(fxSupplierGoodMt.getCounts());
            fxSupplierGood.setCounts(fxSupplierGoodMt.getCounts());
            fxSupplierGood.setTotalSellCount(0L);
            fxSupplierGood.setGoodImg(fxSupplierGoodMt.getGoodImg());
            fxSupplierGood.setGoodText(fxSupplierGoodMt.getGoodText());
            fxSupplierGood.setGoodDetail(fxSupplierGoodMt.getGoodDetail());
            fxSupplierGood.setStatus(1L);
            fxSupplierGood.setClassOneId(fxSupplierGoodMt.getClassOneId());
            fxSupplierGood.setClassOneName(fxSupplierGoodMt.getClassOneName());
            fxSupplierGood.setDelFlag(0);
            fxSupplierGood.setIsInitiate(Integer.parseInt(fxSupplierGoodMt.getIsInitiate()));
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            // 将日期格式化为指定格式的字符串
            String formattedDate = currentDate.format(formatter);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/barCode/" + formattedDate;
            String imgUrl = CodeGeneratorUtil.generateBarCode(goodId.toString(), 400, 100, filePath);
            fxSupplierGood.setQrCodeUrl("/profile/upload/barCode/" + formattedDate + imgUrl); // 二维码生成
            fxStoreGoods.add(fxStoreGood);
            fxSupplierGoods.add(fxSupplierGood);
        }

        if (!CollectionUtils.isEmpty(fxStoreGoods)&&!CollectionUtils.isEmpty(fxSupplierGoods)){
            fxStoreGoodMapper.saveBath(fxStoreGoods);
            supplierGoodMapper.saveBath(fxSupplierGoods);
        }


        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("fxSupplierGoods",fxSupplierGoods);
        stringObjectHashMap.put("msg",CollectionUtils.isEmpty(goodNameList)?"":"以下商品店铺已存在无法添加："+goodNameList);
        return stringObjectHashMap;

    }

    public String saveSonBath(List<FxSupplierGoodMtVO> sonFxSupplierGoodMtVO) {

        Long userId = SecurityUtils.getUserId();
        FxUser fxUser = fxUserMapper.selectFxUserByUserId(userId); // 拿到用户信息
        if (ObjectUtils.isEmpty(fxUser)||ObjectUtils.isEmpty(fxUser.getStoreId())) {
            throw new GlobalException("人员信息异常");
        }
        FxStore fxStore = fxStoreMapper.selectFxStoreById(fxUser.getStoreId());
        if (StringUtils.isNull(fxStore.getRegion()))
            throw new GlobalException("店铺地区信息异常");

        List<FxStoreGood> fxStoreGoods = new ArrayList<>();
        List<FxSupplierGood> fxSupplierGoods = new ArrayList<>();
        Date nowDate = DateUtils.getNowDate();
        for (FxSupplierGoodMtVO fxSupplierGoodMt : sonFxSupplierGoodMtVO) {
            Long goodId = Convert.toLong(System.currentTimeMillis() + "" + ThreadLocalRandom.current().nextInt(100, 1000));
            //FxStoreGood
            FxStoreGood fxStoreGood = new FxStoreGood();
            fxStoreGood.setId(goodId);
            fxStoreGood.setCreateUser(Integer.parseInt(userId.toString()));
            fxStoreGood.setCreateTime(nowDate);
            fxStoreGood.setCounts(Integer.valueOf(fxSupplierGoodMt.getCounts().toString()));
            fxStoreGood.setTotalSellCount(0);
            fxStoreGood.setStoreId(Integer.valueOf(fxStore.getId().toString()));
            fxStoreGood.setIsInitiate(Integer.valueOf(fxSupplierGoodMt.getIsInitiate()));
            fxStoreGood.setGoodId(goodId);
            fxStoreGood.setGoodName(fxSupplierGoodMt.getGoodName());
            //FxSupplierGood
            FxSupplierGood fxSupplierGood = new FxSupplierGood();
            fxSupplierGood.setCreateTime(nowDate);
            fxSupplierGood.setCreateUser(userId);
            fxSupplierGood.setId(goodId);
            fxSupplierGood.setParentId(fxSupplierGoodMt.getParentId());
            fxSupplierGood.setSource(2);
            fxSupplierGood.setUserId(userId);
            fxSupplierGood.setRegion(Convert.toStr(fxStore.getRegion()));
            fxSupplierGood.setGoodName(fxSupplierGoodMt.getGoodName());
            fxSupplierGood.setTradePrice(fxSupplierGoodMt.getTradePrice());
            fxSupplierGood.setRetailPrice(fxSupplierGoodMt.getRetailPrice());
            fxSupplierGood.setMemberPrice(fxSupplierGoodMt.getMemberPrice());
            fxSupplierGood.setGrandCounts(fxSupplierGoodMt.getCounts());
            fxSupplierGood.setCounts(fxSupplierGoodMt.getCounts());
            fxSupplierGood.setTotalSellCount(0L);
            fxSupplierGood.setGoodImg(fxSupplierGoodMt.getGoodImg());
            fxSupplierGood.setGoodText(fxSupplierGoodMt.getGoodText());
            fxSupplierGood.setGoodDetail(fxSupplierGoodMt.getGoodDetail());
            fxSupplierGood.setStatus(1L);
            fxSupplierGood.setClassOneId(fxSupplierGoodMt.getClassOneId());
            fxSupplierGood.setClassOneName(fxSupplierGoodMt.getClassOneName());
            fxSupplierGood.setDelFlag(0);
            fxSupplierGood.setIsInitiate(Integer.parseInt(fxSupplierGoodMt.getIsInitiate()));
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            // 将日期格式化为指定格式的字符串
            String formattedDate = currentDate.format(formatter);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/barCode/" + formattedDate;
            String imgUrl = CodeGeneratorUtil.generateBarCode(goodId.toString(), 400, 100, filePath);
            fxSupplierGood.setQrCodeUrl("/profile/upload/barCode/" + formattedDate + imgUrl); // 二维码生成
            fxStoreGoods.add(fxStoreGood);
            fxSupplierGoods.add(fxSupplierGood);
        }
        if (!CollectionUtils.isEmpty(fxStoreGoods)&&!CollectionUtils.isEmpty(fxSupplierGoods)){
            //查询该店铺是否添加过这个子商品
            Set<String> sonNames = fxSupplierGoods.stream().map(FxSupplierGood::getGoodName).collect(Collectors.toSet());

           // List<String> sonGoodName = supplierGoodMapper.selectlistByGoodName(sonNames,fxStore.getId());
           // fxStoreGoods.removeIf(item-> sonGoodName.contains(item.getGoodName()));
           // fxSupplierGoods.removeIf(item-> sonGoodName.contains(item.getGoodName()));

            fxStoreGoodMapper.saveBath(fxStoreGoods);
            supplierGoodMapper.saveBath(fxSupplierGoods);

            //return CollectionUtils.isEmpty(sonGoodName)?"":sonGoodName.toString();
            return "";
        }
        return "";
    }

    //
    @Override
    public List<FxGoodclassify> selectLeftClassifyByStoreId(int  storeId){
        List<FxGoodclassify> classifyList = fxGoodclassifyMapper.selectLeftClassifyByStoreId(storeId);
        List<Long> classIds = classifyList.stream().map(FxGoodclassify::getId).collect(Collectors.toList());
        FxStoreGoodDto goodDto = new FxStoreGoodDto();
        goodDto.setStoreId((long) storeId);
        goodDto.setClassIds(classIds);
        if(!classIds.isEmpty()){
            List<FxStoreGoodVo> list = fxStoreGoodMapper.selectAppGoodList(goodDto);
            for (FxGoodclassify goodclassify : classifyList) {
                for (FxStoreGoodVo goods : list) {
                    if(Objects.equals(goods.getGoodClassify(), goodclassify.getId())){
                        if(goodclassify.getGoodList() == null || goodclassify.getGoodList().isEmpty()){
                            ArrayList<FxStoreGoodVo> arrayList = new ArrayList<>();
                            arrayList.add(goods);
                            goodclassify.setGoodList(arrayList);
                        }else {
                            goodclassify.getGoodList().add(goods);
                        }

                    }
                }
            }
        }
        for (FxGoodclassify fxGoodclassify : classifyList) {
            List<FxStoreGoodVo> goodList = fxGoodclassify.getGoodList();
            if (!CollectionUtils.isEmpty(goodList)){
                for (FxStoreGoodVo fxStoreGoodVo : goodList) {
                    FxSupplierGood fxSupplierGood = new FxSupplierGood();
                    fxSupplierGood.setParentId(fxStoreGoodVo.getId());
                    fxSupplierGood.setStatus(2L);
                    fxSupplierGood.setDelFlag(0);
                    fxSupplierGood.setIsInitiate(0);
                    List<FxSupplierGood> fxSupplierGoods = supplierGoodMapper.selectFxSupplierSonGoodList(fxSupplierGood);
                    fxStoreGoodVo.setGoodsList(fxSupplierGoods);
                }
            }
        }



        return  classifyList;
    }

    @Override
    @Transactional
    public FxStoreGoodVo getStoreGoodById(Long id, Long supplierGoodId, Long storeId) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 检查是否是1号
        FxStoreGood storeGood = new FxStoreGood();
        if (StringUtils.isNotNull(id)) {
            storeGood = fxStoreGoodMapper.selectFxStoreGoodByIdOrSupplierGoodId(id, supplierGoodId, null);
        }

        FxStore fxStore = fxStoreMapper.selectFxStoreById(storeGood.getStoreId().longValue());
        FxSupplierGood fxSupplierGood = supplierGoodMapper.selectFxSupplierGoodById(storeGood.getGoodId());
        FxSupplierGood good = new FxSupplierGood();
        good.setGoodIds(new Long[]{fxSupplierGood.getId()});
        if(storeId == null || storeId == 0){
            good.setStatus(2L);
            good.setIsInitiate(0);
        }
        good.setDelFlag(0);
        List<FxSupplierGood> goodList = supplierGoodMapper.selectFxSupplierSonGoodList(good);
        //修改子商品属性
        for (FxSupplierGood supplierGood : goodList) {
            List<Map<String,List<String>>> map =new ArrayList<>();
            if (StringUtils.isNotEmpty(supplierGood.getSpecifications())&&supplierGood.getSpecifications().indexOf("：")>0){
                Map<String, List<String>> maps = new HashMap<>();
                String specifications = supplierGood.getSpecifications();
                String[] split = specifications.split("。");
                for (String s : split) {
                    String substring = s.substring(0, s.indexOf("："));
                    List<String> strings = Arrays.asList(s.substring(s.indexOf("：") + 1).split("，"));
                    maps.put(substring,strings);
                }
                map.add(maps);
                supplierGood.setMap(map);
            }
        }
        FxStoreGoodVo goodVo = new FxStoreGoodVo();
        BeanUtil.copyProperties(fxSupplierGood, goodVo);
        BeanUtils.copyProperties(storeGood, goodVo);
        goodVo.setGoodsList(goodList);
        List<Map<String,List<String>>> mapnew =new ArrayList<>();
        if (StringUtils.isNotEmpty(goodVo.getSpecifications())&&goodVo.getSpecifications().indexOf("：")>0){
            Map<String, List<String>> maps = new HashMap<>();
            String specifications = goodVo.getSpecifications();
            String[] split = specifications.split("。");
            for (String s : split) {
                String substring = s.substring(0, s.indexOf("："));
                List<String> strings = Arrays.asList(s.substring(s.indexOf("：") + 1).split("，"));
                maps.put(substring,strings);
            }
            mapnew.add(maps);
        }
        goodVo.setMap(mapnew);
        if (StringUtils.isNotEmpty(goodVo.getSpecifications())) {
            List<String> list = Arrays.asList(goodVo.getSpecifications().split(";"));
            goodVo.setSpecificationsList(list);
        }
        goodVo.setStoreName(fxStore.getStoreName());
//                .setGoodName(fxSupplierGood.getGoodName())
//                .setGoodDetail(fxSupplierGood.getGoodDetail())
//                .setGoodImg(fxSupplierGood.getGoodImg())
//                .setGoodDesc(fxSupplierGood.getGoodDesc())
//                .setGoodText(fxSupplierGood.getGoodText())
//                .setRetailPrice(fxSupplierGood.getRetailPrice())
//                .setMemberPrice(fxSupplierGood.getMemberPrice())
//                .setQrCodeUrl(fxSupplierGood.getQrCodeUrl())
//                .setSource(fxSupplierGood.getSource())
//                .setClassOneId(fxSupplierGood.getClassOneId())
//                .setClassTwoId(fxSupplierGood.getClassTwoId())
//                .setClassThreeId(fxSupplierGood.getClassThreeId())
//                .setClassOneName(fxSupplierGood.getClassOneName())
//                .setClassTwoName(fxSupplierGood.getClassTwoName())
//                .setClassThreeName(fxSupplierGood.getClassThreeName())
//                .setTradePrice(StringUtils.isNotNull(fxSupplierGood.getTradePrice()) ? fxSupplierGood.getTradePrice().toString() : "0");
        return goodVo;
    }

    ;
    /**
     * 小程序 店铺商品
     *
     * @param fxStoreGood
     * @return
     */
    @Override
    public List<FxGoodclassify> selectLeftClassify(FxStoreGood fxStoreGood) {
        if (fxStoreGood.getStoreId() == null)
            return new ArrayList<>();
        // 获取门店 id
        Long storeId = Long.valueOf(fxStoreGood.getStoreId());
        FxStoreGoodDto fxStoreGoodDto = new FxStoreGoodDto();
        fxStoreGoodDto.setStoreId(storeId);
        List<FxStoreGoodVo> goodVoList = fxStoreGoodMapper.selectAppGoodList(fxStoreGoodDto);
        if (CollectionUtils.isEmpty(goodVoList)) {
            return new ArrayList<>();
        }
        // 提取门店拥有的商品的分类ID
        List<Long> classTwoIds = goodVoList.stream()
                .map(FxStoreGoodVo::getGoodClassify)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, List<FxStoreGoodVo>> goodsMap = goodVoList.stream().collect(Collectors.groupingBy(FxStoreGoodVo::getGoodClassify));

        // 查询这些分类ID对应的分类信息
        List<FxGoodclassify> classifyList = fxGoodclassifyMapper.selectFxGoodclassifyByIds(classTwoIds);
        for (FxGoodclassify goodClassify : classifyList) {
            goodClassify.setGoodList(goodsMap.get(goodClassify.getId()));
        }
        return classifyList;
    }

    /**
     * 小程序商品树
     *
     * @param fxStoreGood
     * @return
     */
    @Override
    public List<FxGoodclassify> selectFxStoreGoodListTree(FxStoreGood fxStoreGood) {
        fxStoreGood.setDelFlag(0);

        // 查询当前门店的商品列表
        List<FxStoreGood> goodList = fxStoreGoodMapper.selectFxStoreGoodList(fxStoreGood);

        // 提取商品ID并去重
        List<Long> goodIdList = goodList.stream()
                .map(FxStoreGood::getGoodId)
                .distinct()
                .collect(Collectors.toList());

        // 根据商品ID查询供应商商品
        List<FxSupplierGood> supplierGoodList = supplierGoodMapper.selectFxSupplierGoodListByGoodIds(goodIdList);

        // 提取门店拥有的商品的分类ID
        List<Long> classTwoIds = supplierGoodList.stream()
                .map(FxSupplierGood::getClassTwoId)
                .distinct()
                .collect(Collectors.toList());

        // 查询这些分类ID对应的分类信息
        List<FxGoodclassify> classifyList = fxGoodclassifyMapper.selectFxGoodclassifyByIds(classTwoIds);

        // 提取分类的父ID，并查询这些父分类
        Set<Long> parentIds = classifyList.stream()
                .map(FxGoodclassify::getParentId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 查询所有父分类
        List<FxGoodclassify> parentClassifications = fxGoodclassifyMapper.selectFxGoodclassifyByIds(new ArrayList<>(parentIds));

        // 创建分类ID的映射，以便快速查找
        Map<Long, FxGoodclassify> classifyMap = classifyList.stream()
                .collect(Collectors.toMap(FxGoodclassify::getId, g -> g));

        // 将父分类添加到分类列表中
        classifyList.addAll(parentClassifications);

        // 根据父分类ID设置子分类列表
        for (FxGoodclassify classify : parentClassifications) {
            Long parentId = classify.getId(); // 拿到父类id
            List<FxGoodclassify> children = classifyList.stream()
                    .filter(c -> Objects.equals(c.getParentId(), parentId))
                    .collect(Collectors.toList());
            classify.setChildList(children);
            for (FxGoodclassify child : children) {
                List<FxSupplierGood> goodsList = supplierGoodList.stream()
                        .filter(c -> Objects.equals(c.getClassTwoId(), child.getId()))
                        .collect(Collectors.toList());
//                child.setGoodList(goodsList);
            }
        }

        return parentClassifications;
    }

    /**
     * 查询商品
     *
     * @param dto
     * @return
     */
    public List<FxStoreGoodVo> selectAppGoodList(FxStoreGoodDto dto) {
        // 判断输入框 为空 返回空数组
        if (StringUtils.isNull(dto.getGoodName()))
            return new ArrayList<>();
        List<FxStoreGoodVo> storeGoodList = fxStoreGoodMapper.selectAppGoodList(dto);
        return listSort(storeGoodList, dto);
    }

    /**
     * 搜索排序
     *
     * @param storeGoodList 商品列表
     * @param dto           排序条件
     * @return
     */
    List<FxStoreGoodVo> listSort(List<FxStoreGoodVo> storeGoodList, FxStoreGoodDto dto) {
        if (dto.getSortType() == null) {
            return storeGoodList;
        }
        Comparator<FxStoreGoodVo> comparator;
        if (dto.getSortType() == 1) {
            // 按销量排序
            comparator = Comparator.comparing(FxStoreGoodVo::getTotalSellCount);
        } else {
            // 按价格排序
            comparator = Comparator.comparing(FxStoreGoodVo::getRetailPrice);
        }
        // 根据排序决定升序或降序
        if (dto.getSort() != 1) {
            comparator = comparator.reversed();
        }
        return storeGoodList.stream()
                .sorted(comparator) // 排序
                .collect(Collectors.toList());
    }


    /**
     * 新增店铺商品
     *
     * @param fxStoreGood 店铺商品
     * @return 结果
     */
    @Override
    public int insertFxStoreGood(FxStoreGood fxStoreGood) {
        // 判断商品是否添加过
        FxStoreGood storeGood = new FxStoreGood();
        storeGood.setGoodId(fxStoreGood.getGoodId());
        storeGood.setStoreId(fxStoreGood.getStoreId());
        List<FxStoreGood> storeGoodList = fxStoreGoodMapper.selectFxStoreGoodList(storeGood);
        if (StringUtils.isNotEmpty(storeGoodList)) {
            FxStoreGood good = storeGoodList.get(0);
            int counts1 = fxStoreGood.getCounts(); // 新添库存
            int counts2 = good.getCounts() + counts1; // 最新库存
            GoodInventoryDto goodInventoryDto = new GoodInventoryDto();
            goodInventoryDto.setGoodId(good.getId()); // 店铺商品id
            goodInventoryDto.setCounts(counts2); // 最新库存
            goodInventoryDto.setVersion(good.getVersion());// 库存版本号
            return fxStoreGoodMapper.updateFxStoreGoodInventory(goodInventoryDto);
        }
        fxStoreGood.setCreateTime(DateUtils.getNowDate());
        return fxStoreGoodMapper.insertFxStoreGood(fxStoreGood);
    }

    /**
     * 新增 店铺商品
     * @param fxSupplierGood
     * @return
     */
    @Override
    @Transactional
    public int insertFxStoreGood(FxSupplierGood fxSupplierGood) {
        Long userId = SecurityUtils.getUserId();

        FxUser fxUser = fxUserMapper.selectFxUserByUserId(userId); // 拿到用户信息
        if (ObjectUtils.isEmpty(fxUser)||ObjectUtils.isEmpty(fxUser.getStoreId())) {
            throw new GlobalException("人员信息异常");
        }
        FxStore fxStore = fxStoreMapper.selectFxStoreById(fxUser.getStoreId());
        if (StringUtils.isNull(fxStore.getRegion()))
            throw new GlobalException("店铺地区信息异常");

        FxSupplierGood supplierGood = this.exist(fxUser, fxSupplierGood);
        if (StringUtils.isNotNull(supplierGood))
            throw new GlobalException("“" + fxSupplierGood.getGoodName() + "“,已存在");


        fxSupplierGood.setCreateTime(DateUtils.getNowDate());
        String goodId = System.currentTimeMillis() + "" + ThreadLocalRandom.current().nextInt(100, 1000);
        fxSupplierGood.setId(Convert.toLong(goodId));
        fxSupplierGood.setSource(2);
        fxSupplierGood.setUserId(userId);
        fxSupplierGood.setRegion(Convert.toStr(fxStore.getRegion()));

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        // 将日期格式化为指定格式的字符串
        String formattedDate = currentDate.format(formatter);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/barCode/" + formattedDate;
        String imgUrl = CodeGeneratorUtil.generateBarCode(goodId, 400, 100, filePath);
        fxSupplierGood.setQrCodeUrl("/profile/upload/barCode/" + formattedDate + imgUrl); // 二维码生成
        supplierGoodMapper.insertFxSupplierGood(fxSupplierGood);
        FxStoreGood fxStoreGood = new FxStoreGood();
        fxStoreGood.setId(Convert.toLong(goodId));
        fxStoreGood.setGoodId(Convert.toLong(goodId));
        fxStoreGood.setCreateTime(DateUtils.getNowDate());
        fxStoreGood.setCreateUser(Convert.toInt(userId));
        fxStoreGood.setRemark(fxStoreGood.getRemark());
        fxStoreGood.setCounts(ObjectUtils.isEmpty(fxSupplierGood.getCounts())?0:Integer.parseInt(fxSupplierGood.getCounts().toString()));
        fxStoreGood.setStoreId(Convert.toInt(fxUser.getStoreId()));
        return fxStoreGoodMapper.insertFxStoreGood(fxStoreGood);
    }
    /**
     * 修改店铺商品
     *
     * @param supplierGood 店铺商品
     * @return 结果
     */
    @Override
    @Transactional
    public int updateFxStoreGood(FxSupplierGoodDto supplierGood) {
//        supplierGoodMapper.updateFxSupplierGood(supplierGood);
//        return fxStoreGoodMapper.updateFxStoreGoods(supplierGood);
        SysUser sysUser  = SecurityUtils.getLoginUser().getUser();
        FxUser fxUser = fxUserMapper.selectFxUserByUserId(sysUser.getUserId()); // 拿到用户信息
        List<SysRole> roles = sysUser.getRoles();
        boolean flag=true;
        //平台管理员和超级管理员才有权限
        for (SysRole role : roles) {
            if (role.getRoleId().equals(1L) || role.getRoleId().equals(6L)) {
                flag = false;
                break;
            }
        }
        FxSupplierGood good=null;
        if (!ObjectUtils.isEmpty(fxUser)){
            //门店自己人有权限
            good= supplierGoodMapper.selectFxSupplierGoodById(supplierGood.getId());
            FxStoreGood fxStoreGood = fxStoreGoodMapper.selectFxStoreGoodById(supplierGood.getId());
            if (ObjectUtils.isEmpty(fxStoreGood)||!fxStoreGood.getStoreId().toString().equals(fxUser.getStoreId().toString())){
                good=null;
            }

        }else if (!flag){
            good = supplierGoodMapper.selectFxSupplierGoodById(supplierGood.getId());
        }
        if (ObjectUtils.isEmpty(good))
            throw new GlobalException("没有更改权限！");


//        FxSupplierGood fxSupplierGood = new FxSupplierGood();
//        fxSupplierGood.setGoodName(supplierGood.getGoodName());
//        fxSupplierGood.setStoreId(good.getStoreId());
//        List<FxSupplierGood> fxSupplierGoods = supplierGoodMapper.selectFxSupplierGoodList(fxSupplierGood);

        FxSupplierGood fxSupplierGood=supplierGoodMapper.selectFxSupplierGoodByName(supplierGood.getGoodName(),good.getStoreId(),supplierGood.getId());

        if(!ObjectUtils.isEmpty(fxSupplierGood)){
//        if (!CollectionUtils.isEmpty(fxSupplierGoods)&&!fxSupplierGoods.get(0).getId().equals(supplierGood.getId())){
            throw new GlobalException( "“"+ good.getGoodName() + "”，名称已存在" );
        }


        FxStoreGood storeGood = new FxStoreGood();
        storeGood.setId(supplierGood.getId());
        storeGood.setCounts(ObjectUtils.isEmpty(supplierGood.getCounts())?0:Math.toIntExact(supplierGood.getCounts()));
        fxStoreGoodMapper.updateFxStoreGood(storeGood);



        return supplierGoodMapper.updateFxSupplierGood(supplierGood);
    }

    /**
     * 门店商品审核
     * @param fxStoreGood
     * @return
     */
    @Override
    public int updateStoreGoodAudit(FxSupplierGoodDto fxStoreGood) {
        return supplierGoodMapper.updateFxSupplierGood(fxStoreGood);
    }

    /**
     * 店铺商品上下架
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public int upOrDown(FxStoreGoodDto dto) {
        FxStoreGood good = fxStoreGoodMapper.selectFxStoreGoodById(dto.getId());
        if (StringUtils.isNull(good)) {
            throw new GlobalException("店铺商品信息异常");
        }
        FxStoreGood storeGood = new FxStoreGood();
        storeGood.setId(dto.getId());
        storeGood.setIsInitiate(dto.getIsInitiate());
        return fxStoreGoodMapper.updateFxStoreGood(storeGood);
    }

    /**
     * 批量修改 删除标志
     *
     * @param ids
     * @return
     */
    @Override
    public int updateDelFlag(String[] ids) {
        return fxStoreGoodMapper.updateStatusByIds(ids, 1, 1);
    }

    /**
     * 补货
     *
     * @param fxStoreGood
     * @return
     */
    @Override
    public int updateFxStoreGoodCounts(FxStoreGood fxStoreGood) {
        Long id = fxStoreGood.getId();
        FxSupplierGood fxSupplierGood = supplierGoodMapper.selectFxSupplierGoodById(id);
        if (ObjectUtils.isEmpty(fxSupplierGood)){
            throw new GlobalException("商品信息错误");
        }
        long newCounts = fxSupplierGood.getCounts() + fxStoreGood.getCounts();
        fxSupplierGood.setCounts(newCounts);
        fxSupplierGood.setRemark(fxStoreGood.getRemark());
//        FxStoreGood storeGood = fxStoreGoodMapper.selectFxStoreGoodById(fxStoreGood.getId());
//        if (StringUtils.isNull(storeGood)) {
//            throw new GlobalException("商品信息错误");
//        }
//        int newCounts = storeGood.getCounts() + fxStoreGood.getCounts();
//        fxStoreGood.setCounts(newCounts);
//        return fxStoreGoodMapper.updateFxStoreGood(fxStoreGood);

        //改为修改供应商商品库存
       return supplierGoodMapper.updateFxSupplierGood(fxSupplierGood);
    }

    /**
     * 批量删除店铺商品
     *
     * @param ids 需要删除的店铺商品主键
     * @return 结果
     */
    @Override
    public int deleteFxStoreGoodByIds(Integer[] ids) {
        return fxStoreGoodMapper.deleteFxStoreGoodByIds(ids);
    }

    /**
     * 删除店铺商品信息
     *
     * @param id 店铺商品主键
     * @return 结果
     */
    @Override
    public int deleteFxStoreGoodById(Integer id) {
        return fxStoreGoodMapper.deleteFxStoreGoodById(id);
    }

    /**
     * 是否存在
     * @param user 用户
     * @param  fxSupplierGood 子商品
     * @return
     */
    public FxSupplierGood exist(FxUser user, FxSupplierGood fxSupplierGood) {
        if (StringUtils.isNull(user))
            throw new GlobalException("用户信息错误！");
        Long storeId = user.getStoreId();
        return supplierGoodMapper.selectSupplierByGoodNameAndStoreId(fxSupplierGood.getGoodName(), storeId,fxSupplierGood.getParentId());
    }

}
